package com.alibaba.demo.filter;

import com.alibaba.demo.entity.AyUser;
import com.alibaba.demo.service.AyUserService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * @author zhouyanxiang
 * @create 2020-08-2020/8/24-16:53
 */
@WebListener
public class AyUserListener implements ServletContextListener {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AyUserService ayUserService;

    private static final String ALL_USER = "ALL_USER_LIST";

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent){
        // 查询所有的用户
        List<AyUser> ayUserList = ayUserService.findAll();
        // 清除缓存中的数据
        redisTemplate.delete(ALL_USER);
        // 将数据放到Redis缓存中
        redisTemplate.opsForList().leftPushAll(ALL_USER,ayUserList);
        // 在真实的项目中需要注释掉，查询所有的用户数据
        List<AyUser> queryUserList = redisTemplate.opsForList().range(ALL_USER,0,-1);
        logger.info("servletContext容器上下文初始化");
        logger.info("缓存中的目前的用户数有："  + queryUserList.size() + "人");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent){
        logger.info("servlet上下文销毁");
//        System.out.println("servlet上下文销毁");
    }


}
